package org.code.mallspringboot.controller;

import org.code.mallspringboot.dto.SmsCouponDto;
import org.code.mallspringboot.pojo.SmsCoupon;
import org.code.mallspringboot.service.SmsCouponService;
import org.code.mallspringboot.vo.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.xml.stream.events.Comment;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/coupon")
public class SmsCouponController {

    @Autowired
    private SmsCouponService smsCouponService;

    //优惠券列表
    @GetMapping("/list")
    public CommonResult list(@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                             @RequestParam(value = "pageSize",defaultValue = "10") int pageSize,
                             String name, Integer type){
        List<SmsCoupon> list = smsCouponService.selectPage(pageNum, pageSize, type, name);
        int total = smsCouponService.total(type, name);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("list" , list);
        map.put("total" , total);
        if (!map.isEmpty()){
            return CommonResult.success(map);
        }
        return CommonResult.failed("查询失败");
    }

    //编辑-回显
    @GetMapping("/{id}")
    public CommonResult getCoupon(@PathVariable int id){
        SmsCoupon smsCoupon = smsCouponService.selectById(id);
        if (smsCoupon != null){
            return CommonResult.success(smsCoupon);
        }
        return CommonResult.failed("回显失败!");
    }

    //编辑提交
    @PostMapping("/update/{id}")
    public CommonResult update(@PathVariable int id,@RequestBody SmsCouponDto smsCouponDto){
        smsCouponDto.setId(id);
        if (smsCouponService.update(smsCouponDto) > 0){
            return CommonResult.success("修改成功");
        }
        return CommonResult.failed("修改失败!");
    }

    //添加
    @PostMapping("/create")
    public CommonResult create(@RequestBody SmsCouponDto smsCouponDto){
        if (smsCouponService.add(smsCouponDto) > 0){
            return CommonResult.success("添加成功!");
        }
        return CommonResult.failed("添加失败!");
    }

    //删除
    @PostMapping("/delete/{id}")
    public CommonResult delete(@PathVariable int id){
        if (smsCouponService.delete(id) > 0){
            return CommonResult.success("删除成功!");
        }
        return CommonResult.failed("删除失败!");
    }
}
